import { Button, Card, Form, Image, Input, Select, Space, Table } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import { ColumnsType } from 'antd/lib/table';
import React, { useEffect, useState } from 'react'
import { IDictList, IHopsitalList } from '@/api/hospital/model/hospitalListTypes';
import { changeStatus, getCityOrDict, getHospitalList, getProvinceList } from '@/api/hospital/hospitalList';
import { useNavigate } from 'react-router-dom';
const { Option } = Select;
export default function HospitalList() {
    // 创建编程式导航 navigate
    const navigate = useNavigate()
    const columns: ColumnsType<any> = [
        {
            title: '序号',
            render(value, row, index) {
                return (current - 1) * pageSize + (index + 1)
            }
        },
        {
            title: '医院logo',
            render(row) {
                return <Image width={100} src={`data:image/jpeg;base64,${row.logoData}`} />
            }
        },
        {
            title: '医院名称',
            dataIndex: 'hosname'
        },
        {
            title: '等级',
            render(row) {
                return row.param.hostypeString
            }
        },
        {
            title: '详细地址',
            render(row) {
                return row.param.fullAddress
            }
        },
        {
            title: '状态',
            render(row) {
                return row.status === 1 ? '已上线' : '未上线'
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime'
        },
        {
            title: '操作',
            render(row) {
                return (
                    <Space>
                        <Button type='primary' onClick={()=>navigate('/syt/hospital/hospitalList/show/' + row.id)}>查看</Button>
                        <Button type='primary' onClick={()=>navigate('/syt/hospital/hospitalList/schedule/' + row.hoscode)}>排班</Button>
                        <Button type='primary' onClick={()=>_changeStatus(row.id, row.status)}>{row.status === 1 ? '下线' : '上线'}</Button>
                    </Space>
                )
            }
        }
    ]
    /**
     *  切换状态
     */
    async function _changeStatus(id:string, status:number){
        status = status === 1 ? 0 : 1
        await changeStatus(id, status)
        // 刷新医院列表
        _getHospitalList()
    }
    /**
     * 过去医院列表数据
     */
    async function _getHospitalList() {
        let values = form.getFieldsValue()
        let { content, totalElements } = await getHospitalList({ page: current, limit: pageSize,...values })
        console.log(content, totalElements)
        // 设置医院列表状态和总条数状态
        setHospitalList(content)
        setTotal(totalElements)
    }
    // 定义状态
    let [hospitalList, setHospitalList] = useState<IHopsitalList>([])
    let [current, setCurrent] = useState<number>(1)
    let [pageSize, setPageSize] = useState<number>(5)
    let [total, setTotal] = useState<number>(5)
    // 省市区状态
    let [provinceList, setProvinceList] = useState<IDictList>([])
    let [cities, setCities] = useState<IDictList>([])
    let [dicts, setDicts] = useState<IDictList>([])
    // 医院类型状态
    let [types, setTypes] = useState<IDictList>([])
    // 创建form对象，并绑定Form 组件
    let [form] = Form.useForm()
    // 将查询条件的表单数据，作为一个整体，设置成数组
    let [fields, setFields] = useState([
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined
    ])
    // 获取省列表
    async function _getProvinceList() {
        // 请求获取省列表，并设置状态
        let provinceList = await getProvinceList()
        setProvinceList(provinceList)
    }
    // 省列表改变，触发获取市列表
    /**
     * 1. 我们要清空市、区下拉框的当前值[undefined]，让其显示请选择 市、区
     * 2. 获取最新的市列表，进行市下拉框渲染。
     * 3. 清空区下拉框列表
     */
    async function _getCityList(provinceId: string) {
        // 1. 我们要清空市、区下拉框的当前值[undefined]
        form.setFieldsValue({
            cityCode: undefined,
            districtCode: undefined
        })
        let cities = await getCityOrDict(provinceId)
        //2. 进行市下拉框渲染。
        setCities(cities)
        // 3. 清空区下拉框列表,就是将区的状态数据设置为 []
        setDicts([])
    }
    // 市改变，获取区列表
    // 1. 获取最新的区列表数据
    // 2. 需要将区的表单值，设置为undefined
    async function _getDicts(cityId: string) {
        // 1.
        let dicts = await getCityOrDict(cityId)
        setDicts(dicts)
        // 2. 需要将区的表单值，设置为undefined
        form.setFieldsValue({
            districtCode: undefined
        })
    }
    /**
     * 获取医院类型
     */
    async function _getHospitalType() {
        let types = await getCityOrDict('10000')
        setTypes(types)
    }
    /**
     * 点击查询触发
     */
    async function onFinish(){
        // 点击查询，重置fields状态
        let values = form.getFieldsValue()
        setFields([
            values.hosname,
            values.hoscode,
            values.hostype,
            values.provinceCode,
            values.cityCode,
            values.districtCode,
            values.status
        ])
        // 如果当前页不是第一页，重置页码为第一页
        current !== 1 && setCurrent(1)
    }
    /**
     * 重置查询表单
     * 1. 重置表单的数据
     * 2. 重置fields状态的数据
     * 3. 如果current不是1，那么重置current 为1
     */
    function reset(){
        // 1. 
        form.resetFields()
        // 2. 
        setFields([
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined
        ])
        //3.
        current !==1 && setCurrent(1)
    }
    useEffect(() => {
        _getHospitalList()
    }, [current, pageSize, ...fields])

    useEffect(() => {
        _getProvinceList()
        _getHospitalType()
    }, [])

    return (
        <Card>
            {/* 1. 表单 */}
            <Form
                layout='inline'
                form={form}
                onFinish={onFinish}
            >
                <Form.Item name='provinceCode'>
                    <Select onChange={_getCityList} className='mb20' placeholder='请选择省'>
                        {provinceList.map(province => (
                            <Option key={province.id} value={province.value}>{province.name}</Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item name='cityCode'>
                    <Select onChange={_getDicts} placeholder='请选择市'>
                        {cities.map(city => (
                            <Option key={city.id} value={city.value}>{city.name}</Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item name='districtCode'>
                    <Select placeholder='请选择区'>
                        {dicts.map(dict => (
                            <Option key={dict.id} value={dict.value}>{dict.name}</Option>
                        ))}
                    </Select>
                </Form.Item>


                <Form.Item name='hosname'>
                    <Input placeholder='医院名称' />
                </Form.Item>
                <Form.Item name='hoscode'>
                    <Input placeholder='医院编号' />
                </Form.Item>
                <Form.Item name='hostype'>
                    <Select placeholder='医院类型'>
                        {types.map(type => (
                            <Option key={type.id} value={type.value}>{type.name}</Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item name='status'>
                    <Select placeholder='医院状态'>
                        <Option value={1}>已上线</Option>
                        <Option value={0}>未上线</Option>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Space >
                        <Button icon={<SearchOutlined />} type='primary' htmlType='submit'>查询</Button>
                        <Button onClick={reset} disabled={fields.every(item=>item === undefined)}>清空</Button>
                    </Space>
                </Form.Item>
            </Form>
            {/* 2. table */}
            <Table
                rowKey={'id'}
                className='mt20'
                columns={columns}
                dataSource={hospitalList}
                pagination={{
                    current,
                    total,
                    pageSize,
                    pageSizeOptions: [5, 10, 20],
                    showSizeChanger: true,
                    showTotal(total) {
                        return (<div>总条数： <span>{total}</span> 条</div>)
                    },
                    onChange(page: number, pageSize: number) {
                        // 分页操作时，重置当前页和每页显示几条
                        setCurrent(page)
                        setPageSize(pageSize)
                    }
                }}
            />
        </Card>
    )
}
